#include "func.h"
#include <cstring>
#include <errno.h>
#include <error.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
void test()
{
    printf("errno = %d\n", errno);
    FILE *fp = fopen("dict.txt", "r");
    printf("errno = %d\n", errno);
    printf("%s\n", strerror(errno));
    perror("not_exist.txt");
    const char *prefix = "not_exist.txt";
    fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
    // status:若为非零值，函数在输出信息后会调用 exit(status) 终止程序；
    // 若为 0,则仅输出信息,不终止程序。
    error(0, errno, "not_exist.txt");
    cout << "can you see me?" << endl;
}
#define MAXSIZE 512
void test1()
{
    char buffer[MAXSIZE];
    char *cwd = getcwd(buffer, sizeof(buffer));
    if (cwd == nullptr)
    {
        error(1, errno, "getcwd");
    }
    puts(cwd);
}
void test2()
{
    char *cwd = getcwd(NULL, 0);
    if (cwd == nullptr)
    {
        error(1, errno, "getcwd");
    }
    puts(cwd);
    free(cwd);
}
void test3(int argc, char *argv[])
{
    //./main /..../....
    if (argc != 2)
    {
        error(1, 0, "Usage: %s path", argv[0]);
    }
    char cwd[MAXSIZE];
    getcwd(cwd, MAXSIZE);
    puts(cwd);
    if (chdir(argv[1]))
    {
        error(1, errno, "chdir");
    }
    getcwd(cwd, MAXSIZE);
    puts(cwd);
}
void test4(int argc, char *argv[])
{
    if (argc != 3)
    {
        error(1, 0, "Usage: %s path mode", argv[0]);
    }
    mode_t mode;
    sscanf(argv[2], "%o", &mode);
    if (mkdir(argv[1], mode))
    {
        error(1, errno, "mkdir");
    }
}
void test5(int argc, char *argv[])
{
    if (argc != 2)
    {
        error(1, 0, "Usage: %s path", argv[0]);
    }
    if (rmdir(argv[1]))
    {
        error(1, errno, "rmdir");
    }
}
void test6(int argc, char *argv[])
{
    if (argc != 2)
    {
        error(1, 0, "Usage: %s dir", argv[0]);
    }
    DIR *stream = opendir(argv[1]);
    if (!stream)
    {
        error(1, errno, "opendir");
    }
    errno = 0;
    struct dirent *curr;
    while ((curr = readdir(stream)) != nullptr)
    {
        printf("d_ino = %lld, d_off = %lld, d_reclen = %hu, d_type = %d, d_name = %s\n",
               (long long)curr->d_ino, (long long)curr->d_off,
               curr->d_reclen, curr->d_type, curr->d_name);
    }
    if (errno)
    {
        error(1, errno, "readdir");
    }
    closedir(stream);
}
int main(int argc, char *argv[])
{
    // test();
    // test1();
    // test2();
    // test3(argc, argv);
    // test4(argc, argv);
    // test5(argc, argv);
    test6(argc, argv);
    return 0;
}